﻿namespace LinqToSqlQueryVisualizer
{
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;

    internal class SqlQueryInfo
    {
        public SqlQueryInfo()
        {
        }

        public SqlQueryInfo(SqlQueryText[] queries)
        {
            Queries = queries;
        }

        public SqlQueryText[] Queries { get; private set; }

        public static SqlQueryInfo Deserialize(Stream stream)
        {
            var result = new SqlQueryInfo();
            var formatter = new BinaryFormatter();
            var queryCount = (int)formatter.Deserialize(stream);
            result.Queries = new SqlQueryText[queryCount];
            for (var i = 0; i < queryCount; i++)
            {
                SqlQueryText query;
                query.Text = (string)formatter.Deserialize(stream);
                var paramCount = (int)formatter.Deserialize(stream);
                query.Params = new ParameterText[paramCount];
                for (var j = 0; j < paramCount; j++)
                {
                    ParameterText p;
                    p.Name = (string)formatter.Deserialize(stream);
                    p.Value = (string)formatter.Deserialize(stream);
                    p.SqlType = (string)formatter.Deserialize(stream);
                    query.Params[j] = p;
                }

                result.Queries[i] = query;
            }

            return result;
        }

        public void Serialize(Stream stream)
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, Queries.Length);
            foreach (var query in Queries)
            {
                formatter.Serialize(stream, query.Text);
                formatter.Serialize(stream, query.Params.Length);
                foreach (var param in query.Params)
                {
                    formatter.Serialize(stream, param.Name);
                    formatter.Serialize(stream, param.Value);
                    formatter.Serialize(stream, param.SqlType);
                }
            }
        }
    }
}